#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import gzip
from flask import Response
from flask_restful import reqparse, Resource
from src.formats.insensitive_argument import CaseInsensitiveArgument
from src.routers.GetDataFromManager import GetTileFromSLRC

sys.path.append("../..")
# 全局变量

class WmtsKvp(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser(
            argument_class=CaseInsensitiveArgument)
        self.parser.argument_class.case_sensitive = False
        self.parser.add_argument('service', type=str, location='args')
        self.parser.add_argument('Request', type=str, location='args')
        self.parser.add_argument('Version', type=str, location='args')
        self.parser.add_argument('layer', type=str, location='args')
        self.parser.add_argument('style', type=str, location='args')
        self.parser.add_argument('Format', type=str, location='args')
        self.parser.add_argument('tilematrixset', type=str, location='args')
        self.parser.add_argument('TileMatrix', type=str, location='args')
        self.parser.add_argument('TileRow', type=str, location='args')
        self.parser.add_argument('TileCol', type=str, location='args')

    # get方法
    def get(self, servicename):
        data = self.parser.parse_args()

        service = data.get('service')
        request = data.get('Request')
        version = data.get('Version')

        if (str(service).upper() == 'WMTS'):
            if (version == '1.0.0'):
                if (str(request).lower() == 'getcapabilities'):
                    res = mapServiceManager.serviceList[servicename]['tilesManager'].WMTSCapabilities
                    resp = Response(res, status=200, mimetype='text/xml')
                    resp.headers['content-type'] = 'text/xml'
                    # resp.headers['Access-Control-Allow-Origin'] = '*'
                    return resp

                if (str(request).lower() == 'gettile'):
                    row = data.get('TileRow')
                    column = data.get('TileCol')
                    format = data.get('Format')
                    tilematrix = data.get('TileMatrix')

                    resp = ''
                    try:
                        tile = GetTileFromSLRC(servicename, int(tilematrix), int(row), int(column))

                        resp = Response(tile['imgData'], status=200, mimetype='image/png')
                    # resp.headers['Access-Control-Allow-Origin'] = '*'
                    except Exception as e:
                        print(e)

                        resp = Response('MapServer Not Found' +
                                        '\n\nlevel:' + str(tilematrix) +
                                        '\nrow:' + str(row) +
                                        '\ncolumn:' + str(column),
                                        status=404,
                                        mimetype='text/javascript')
                    finally:
                        return resp

                else:
                    return 'wrong request'
            else:
                return 'wrong version'
        else:
            return 'wrong service'

    # post方法
    # def post(self, servicename):
    #     db = DataBase(servicename)
    #
    #     data = self.parser.parse_args()
    #     service = data.get('Service')
    #     request = data.get('Request')
    #     version = data.get('Version')
    #
    #     if (str(service).upper() == 'WMTS'):
    #         if (version == '1.0.0'):
    #             if (str(request).lower() == 'getcapabilities'):
    #                 f = db.GetWMTSCapabilities()
    #                 res = f.read()
    #                 resp = Response(res, status=200, mimetype='text/xml')
    #                 resp.headers['content-type'] = 'text/xml'
    #                 # resp.headers['Access-Control-Allow-Origin'] = '*'
    #                 return resp
    #
    #             if (str(request).lower() == 'gettile'):
    #                 row = data.get('TileRow')
    #                 column = data.get('TileCol')
    #                 format = data.get('Format')
    #                 tilematrix = data.get('TileMatrix')
    #
    #                 f = db.GetTile(tilematrix, row, column)
    #                 if (f):
    #                     data = f.read()
    #                     if (data[0] == 31 and data[1] == 139):
    #                         f = db.GetTile(tilematrix, row, column)
    #                         data = gzip.open(f)
    #                         data = data.read()
    #                     resp = Response(data,
    #                                     status=200,
    #                                     mimetype=db.contenttype)
    #                     # resp.headers['Access-Control-Allow-Origin'] = '*'
    #                     return resp
    #                 else:
    #                     try:
    #                         f = db.GetNoData()
    #                         data = f.read()
    #                         resp = Response(data,
    #                                         status=200,
    #                                         mimetype=db.contenttype)
    #                         # resp.headers['Access-Control-Allow-Origin'] = '*'
    #                         return resp
    #                     except:
    #                         resp = Response(None,
    #                                         status=404,
    #                                         mimetype=db.contenttype)
    #                         # resp.headers['Access-Control-Allow-Origin'] = '*'
    #                         return resp
    #
    #             else:
    #                 return 'wrong request'
    #         else:
    #             return 'wrong version'
    #     else:
    #         return 'wrong service'
